package com.gcxy.utils;

import com.gcxy.conf.result.HttpDefaultCodeEnum;
import com.gcxy.conf.result.R;
import com.gcxy.conf.result.ResultCodeEnum;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @Author lichuandong
 * @Date 2020/10/20
 */
public class HttpUtils {

    public static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    public static R doGet(String uri, Map<String, Object> headMap, int connectTimeout) {
        HttpGet httpGet = new HttpGet(uri);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();
        httpGet.setConfig(requestConfig);
        if (null != headMap && headMap.size() > 0) {
            for (String headKey : headMap.keySet()) {
                httpGet.setHeader(headKey, headMap.get(headKey) + "");
            }
        }
        return sendHttpGet(httpGet);
    }

    private static R sendHttpGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;

        try {
            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpGet);
            int i = response.getStatusLine().getStatusCode();
            //校验code是不是正常的200
            if (!HttpDefaultCodeEnum.isSuccessCode(i)) {
                return R.Failed(ResultCodeEnum.REQUEST_OUT_API_FAIL.getCode(), ResultCodeEnum.REQUEST_OUT_API_FAIL.getMessage() + i);
            } else {
                entity = response.getEntity();
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            LOGGER.error("GET请求外部接口失败：{}", e.getMessage());
            return R.Failed(ResultCodeEnum.REQUEST_OUT_GET_OVERTIME.getCode(), ResultCodeEnum.REQUEST_OUT_GET_OVERTIME.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.Success(responseContent);
    }

    public static R httpPost(String url, String jsonParam, Map<String, Object> headMap, int connectTimeOut) {
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String resultJson = "";
        HttpPost method = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeOut).setSocketTimeout(connectTimeOut).build();
        method.setConfig(requestConfig);
        if (null != headMap && headMap.size() > 0) {
            for (String headKey : headMap.keySet()) {
                method.setHeader(headKey, headMap.get(headKey) + "");
            }
        }
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                if (!StringUtils.isEmpty(jsonParam)) {
                    StringEntity entity = new StringEntity(jsonParam, "utf-8");
                    entity.setContentEncoding("UTF-8");
                    entity.setContentType("application/json");
                    method.setEntity(entity);
                }
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            LOGGER.debug("post请求的返回状态：{}，返回值：{}", result.getStatusLine().getStatusCode());
            if (HttpDefaultCodeEnum.isSuccessCode(result.getStatusLine().getStatusCode())) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    /**把json字符串转换成json对象**/
                    resultJson = str;
                } catch (Exception e) {
                    LOGGER.error("post请求提交失败:" + url, e.getMessage());
                }
            } else {
                int i = result.getStatusLine().getStatusCode();
                return R.Failed(ResultCodeEnum.REQUEST_OUT_API_FAIL.getCode(), ResultCodeEnum.REQUEST_OUT_API_FAIL.getMessage() + i);
            }
        } catch (IOException e) {
            LOGGER.error("post请求提交失败,路径：" + url + ",错误原因：" + e.getMessage());
            return R.Failed(ResultCodeEnum.REQUEST_OUT_POST_OVERTIME.getCode(), ResultCodeEnum.REQUEST_OUT_POST_OVERTIME.getMessage());
        }
        LOGGER.debug("post请求最后的结果：{}", resultJson);
        return R.Success(resultJson);
    }

    public static R httpPut(String strUrl, String param, Map<String, Object> headMap, int connectTimeOut) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(strUrl);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeOut).setSocketTimeout(connectTimeOut).build();
        httpput.setConfig(requestConfig);
        if (null != headMap && headMap.size() > 0) {
            for (String headKey : headMap.keySet()) {
                httpput.setHeader(headKey, headMap.get(headKey) + "");
            }
        }
        String resultJson = "";
        try {
            if (param != null) {
                StringEntity entity = new StringEntity(param, "application/json", "UTF-8");
                httpput.setEntity(entity);
            }
            CloseableHttpResponse httpResponse = httpclient.execute(httpput);
            strUrl = URLDecoder.decode(strUrl, "UTF-8");
            /**请求发送成功，并得到响应**/
            LOGGER.debug("put请求的返回状态：{}，返回值：{}", httpResponse.getStatusLine().getStatusCode());
            if (HttpDefaultCodeEnum.isSuccessCode(httpResponse.getStatusLine().getStatusCode())) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(httpResponse.getEntity());
                    /**把json字符串转换成json对象**/
                    resultJson = str;
                } catch (Exception e) {
                    LOGGER.error("put请求提交失败:" + strUrl, e.getMessage());
                }
            } else {
                int i = httpResponse.getStatusLine().getStatusCode();
                return R.Failed(ResultCodeEnum.REQUEST_OUT_API_FAIL.getCode(), ResultCodeEnum.REQUEST_OUT_API_FAIL.getMessage() + i);
            }
        } catch (Exception e) {
            LOGGER.error("put请求提交失败,路径：" + strUrl + ",错误原因：" + e.getMessage());
            return R.Failed(ResultCodeEnum.REQUEST_OUT_PUT_OVERTIME.getCode(), ResultCodeEnum.REQUEST_OUT_PUT_OVERTIME.getMessage());
        }
        return R.Success(resultJson);
    }


//    /**
//     * 半成品
//     * @param strUrl
//     * @param param
//     * @param headMap
//     * @param connectTimeOut
//     * @return
//     */
//    public static R httpDelete(String strUrl,String param,Map<String,Object> headMap,int connectTimeOut){
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        HttpDelete httpDelete=new HttpDelete(strUrl);
//        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeOut).setSocketTimeout(connectTimeOut).build();
//        httpDelete.setConfig(requestConfig);
//        if(null != headMap && headMap.size() > 0){
//            for(String headKey : headMap.keySet()){
//                httpDelete.setHeader(headKey,headMap.get(headKey) + "");
//            }
//        }
//        String resultJson = "";
//        try {
//            if(param!=null)
//            {
//                StringEntity entity = new StringEntity(param, "application/json", "UTF-8");
//            }
//            CloseableHttpResponse httpResponse = httpclient.execute(httpDelete);
//            strUrl = URLDecoder.decode(strUrl, "UTF-8");
//            /**请求发送成功，并得到响应**/
//            LOGGER.info("put请求的返回状态：{}，返回值：{}", httpResponse.getStatusLine().getStatusCode());
//            if (httpResponse.getStatusLine().getStatusCode() == ErrorCodeEnum.SUCCESS.code()) {
//                String str = "";
//                try {
//                    /**读取服务器返回过来的json字符串数据**/
//                    str = EntityUtils.toString(httpResponse.getEntity());
//                    /**把json字符串转换成json对象**/
//                    resultJson = str;
//                } catch (Exception e) {
//                    LOGGER.error("put请求提交失败:" + strUrl, e.getMessage());
//                }
//            }else {
//                int i = httpResponse.getStatusLine().getStatusCode();
//                return R.Failed(ErrorCodeEnum.REQUEST_OUT_API_FAIL.code(),ErrorCodeEnum.REQUEST_OUT_API_FAIL.message() + i);
//            }
//        } catch (Exception e) {
//            LOGGER.error("put请求提交失败,路径："+ strUrl +",错误原因："+e.getMessage());
//            return R.Failed(ErrorCodeEnum.REQUEST_OUT_PUT_OVERTIME.code(),ErrorCodeEnum.REQUEST_OUT_PUT_OVERTIME.message());
//        }
//        return R.Success(resultJson);
//    }
}
